"use client";
import type { Menu } from "@/lib/api/system/menu.d";
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
  ProTableProps,
} from "@ant-design/pro-components";
import { Button, message, Popconfirm, Space, Tag } from "antd";
import { useRouter } from "next/navigation";
import { useRequest } from "ahooks";
import { useRef } from "react";
import { deleteMenuApi, getMenuListApi } from "@/lib/api/system/menu";
import { arrayToTree, dropTreeChildren } from "@/lib/utils/flat";
import { Icon } from "@/ui/Icon";

export default function Page() {
  const router = useRouter();
  const actionRef = useRef<ActionType>();

  const { run: deleteMenu } = useRequest(deleteMenuApi, {
    manual: true,
    onSuccess: () => {
      message.success("删除成功");
      actionRef.current?.reload();
    },
    onError: () => {
      message.error("删除失败");
    },
  });

  const colums: ProColumns<Menu>[] = [
    {
      title: "菜单名称",
      dataIndex: "menuName",
      key: "menuName",
    },
    {
      title: "图标",
      dataIndex: "icon",
      key: "icon",
      search: false,
      width: 100,
      render: (_, record) => {
        return <Icon type={record.icon} />;
      },
    },
    {
      title: "排序",
      dataIndex: "orderNum",
      key: "orderNum",
      width: 100,
      search: false,
    },
    {
      title: "权限标识",
      dataIndex: "perms",
      key: "perms",
      search: false,
    },
    {
      title: "路径",
      dataIndex: "path",
      key: "path",
      width: 200,
      ellipsis: true,
      search: false,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: 100,
      valueEnum: {
        "0": "启用",
        "1": "停用",
      },
      render: (_, record) => (
        <Tag color={record.status === "0" ? "green" : "red"}>
          {record.status === "0" ? "正常" : "停用"}
        </Tag>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      valueType: "dateTime",
      width: 150,
      hideInSearch: true,
    },
    {
      title: "操作",
      key: "action",
      search: false,
      width: 250,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => editHandler(record.menuId)}>
            修改
          </Button>
          <Popconfirm
            title="确定删除吗？"
            description="删除后将无法恢复！"
            onConfirm={() => {
              deleteMenu(record.menuId);
            }}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
          <Button
            color="green"
            variant="link"
            onClick={() => addHandler(record.menuId)}
          >
            添加子菜单
          </Button>
        </Space>
      ),
    },
  ];

  const proTableProps: ProTableProps<Menu, any> = {
    columns: colums,
    rowKey: "menuId",
    pagination: false,
    headerTitle: "菜单列表",
    expandable: {
      defaultExpandAllRows: true,
    },
    actionRef: actionRef,
    options: {
      fullScreen: true,
    },
    toolBarRender: () => {
      return [
        <Button onClick={() => addHandler()} key="add" type="primary">
          新增
        </Button>,
      ];
    },
    request: async (params) => {
      const res = await getMenuListApi(params);

      const deptTree = arrayToTree(res.data, "menuId", "parentId");

      return {
        data: dropTreeChildren(deptTree),
        success: true,
      };
    },
    onRequestError(e) {
      message.error(e.message);
    },
  };

  const addHandler = (parentId: string = "0") => {
    router.push(`menu/add?parentId=${parentId}`);
  };

  const editHandler = (deptId: string) => {
    router.push(`menu/edit?menuId=${deptId}`);
  };

  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <ProTable {...proTableProps}></ProTable>
    </PageContainer>
  );
}
